﻿using ProjectCloth.Entity;
using ProjectCloth.Entity.Enum;
using ProjectCloth.FrmUI.Common;
using ProjectCloth.FrmUI.Companys;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ProjectCloth.FrmUI
{

    public partial class InStockItemFrm : Form
    {
        private ClothContext db = new ClothContext();
        private int _orderItemId = 0;
        private bool IsNew = true;
        private bool IsPay = false;
        public InStockItemFrm(int orderItemId)
        {
            InitializeComponent();
            _orderItemId = orderItemId;
            //companyCbb.DataSource = db.Companies.ToList();
            //companyCbb.ValueMember = "Id";
            //companyCbb.DisplayMember = "Name";
            makerCbx.DataSource = db.Users.ToList();
            makerCbx.ValueMember = "Id";
            makerCbx.DisplayMember = "Name";
            var cashId = db.CashAccounts.Where(o => o.TradeTypeName == "现金").Select(o => o.Id).FirstOrDefault();
            outmoneycbb.DataSource = db.CashAccounts.ToList();
            outmoneycbb.DisplayMember = "TradeTypeName";
            outmoneycbb.ValueMember = "Id";
            outmoneycbb.SelectedValue = cashId > 0 ? cashId : 0;
            unitCbb.SelectedIndex = 0;
            var orderItem = db.SaleOrderItems.Where(o => o.Id == orderItemId).FirstOrDefault();
            orderNoTxt.Text = db.SaleOrders.Where(o => o.Id == orderItem.OrderId).FirstOrDefault().OrderNo;
            //productCbb.DataSource = db.InStockProducts.ToList();
            //productCbb.DisplayMember = "InstockNo";
            //productCbb.ValueMember = "Id";
            var instockItem = db.InStockItems.AsNoTracking().Where(o => o.SaleOrderItemId == orderItemId).FirstOrDefault();
            if (instockItem != null)
            {
                IsNew = false;
                if (instockItem.IsPaid)
                {
                    IsPay = true;
                    saveBtn.Text = "保存";
                    paySaveBtn.Visible = false;
                    outmoneycbb.Enabled = false;
                    makerCbx.Enabled = false;

                    #region readonly
                    priceTxt.ReadOnly = true;
                    QuanityTxt.ReadOnly = true;
                    costTxt.ReadOnly = true;
                    outmoneyAmountTxt.ReadOnly = true;
                    #endregion
                }
                loadInstockItem(instockItem);
            }
            else
            {
                var instock = db.InStockItems.AsNoTracking().OrderByDescending(o => o.Id).FirstOrDefault();
                makerCbx.SelectedValue = instock.MakerId;
                MakerTime.Value = instock.MakeTime.Value;
            }


        }
        private void loadInstockItem(InStockItem inStockItem)
        {
            //RemarkTxt.Text = inStockItem.Remark;
            companyId.Text = inStockItem.CompanyId != null ? inStockItem.CompanyId.ToString() : "0";
            CompanyTxt.Text = inStockItem.CompanyNo != null ? inStockItem.CompanyNo : "";
            //companyCbb.SelectedValue = inStockItem.CompanyId != null ? inStockItem.CompanyId : 0;
            outmoneycbb.SelectedValue = inStockItem.IsPaid ? (inStockItem.PayAccountId != null ? inStockItem.PayAccountId : 0) : 0;
            productTxt.Text = inStockItem.InstockProductName;
            ColorTypeTxt.Text = inStockItem.ColorType;
            unitCbb.Text = inStockItem.UnitStr;
            priceTxt.Text = inStockItem.Price.ToString();
            QuanityTxt.Text = inStockItem.Quantity.ToString();
            costTxt.Text = inStockItem.Amount.ToString();
            instockNo.Text = inStockItem.InstockItemNo;
            itemRemarkTxt.Text = inStockItem.ItemRemark;
            outmoneyAmountTxt.Text = inStockItem.Amount.ToString();
            makerCbx.SelectedValue = inStockItem.MakerId;
            MakerTime.Value = inStockItem.MakeTime.Value;
            //summaryTxt.Text = inStockItem.Summary;

        }
        /// <summary>
        /// 保存并支付
        /// </summary>
        /// <param name="isPay"></param>
        private void saveAndPay(int isPay = 0)
        {
            if (string.IsNullOrEmpty(CompanyTxt.Text))
            {
                MessageBox.Show("请输入供应商信息！");
                return;
            }
            var message = "";
            var result = 0;
            try
            {
                var instockItem = new InStockItem();
                int makerId = Convert.ToInt32(makerCbx.SelectedValue);
                bool isAreadyPay = false;
                string makerName = db.Users.Where(o => o.Id == makerId).FirstOrDefault()?.Name;
                if (!IsNew)
                {
                    using (var dbs = new ClothContext())
                    {
                        instockItem = dbs.InStockItems.Where(o => o.SaleOrderItemId == _orderItemId).FirstOrDefault();
                        instockItem.CompanyId = string.IsNullOrEmpty(companyId.Text) ? 0 : Convert.ToInt32(companyId.Text); //companyCbb.SelectedValue != null ? Convert.ToInt32(companyCbb.SelectedValue) : 0;
                        instockItem.InstockProductName = productTxt.Text;
                        instockItem.CompanyNo = CompanyTxt.Text != null ? CompanyTxt.Text : "";
                        instockItem.SaleOrderItemId = _orderItemId;
                        instockItem.SaleOrderNo = orderNoTxt.Text;
                        //instockItem.Remark = RemarkTxt.Text;
                        instockItem.ItemRemark = itemRemarkTxt.Text;
                        //instockItem.Summary = summaryTxt.Text;
                        instockItem.CreateTime = DateTime.Now;
                        instockItem.CreatorId = LoginInfo.GetLoginInfo().UserId;
                        instockItem.CreatorName = LoginInfo.GetLoginInfo().UserName;
                        instockItem.MakerId = Convert.ToInt32(makerCbx.SelectedValue);
                        instockItem.MakerName = makerCbx.Text;
                        instockItem.MakeTime = MakerTime.Value;
                        instockItem.UnitStr = unitCbb.Text;
                        instockItem.InstockItemNo = instockNo.Text;
                        instockItem.Amount = Convert.ToDecimal(costTxt.Text);
                        instockItem.ColorType = ColorTypeTxt.Text;
                        if (!instockItem.IsPaid)
                        {
                            instockItem.FinalAmount = Convert.ToDecimal(outmoneyAmountTxt.Text);
                            instockItem.Price = Convert.ToDecimal(priceTxt.Text);
                            instockItem.Quantity = Convert.ToDecimal(QuanityTxt.Text);
                            instockItem.PayAccountId = outmoneycbb.SelectedValue != null ? (int)outmoneycbb.SelectedValue : 0;
                            //instockItem.UnitStr = unitCbb.SelectedText;
                            if (isPay == 0)
                            {
                                instockItem.IsPaid = false;
                            }
                            else
                            {
                                instockItem.IsPaid = true;
                                instockItem.Remark = "手动付款";
                            }

                        }
                        else
                        {
                            isAreadyPay = true;
                        }
                        result = dbs.SaveChanges();
                    }

                }
                else
                {
                    using (var dbs = new ClothContext())
                    {
                        instockItem = new InStockItem()
                        {
                            SaleOrderItemId = _orderItemId,
                            SaleOrderNo = orderNoTxt.Text,
                            CompanyId = string.IsNullOrEmpty(companyId.Text) ? 0 : Convert.ToInt32(companyId.Text), //companyCbb.SelectedValue != null ? Convert.ToInt32(companyCbb.SelectedValue) : 0,
                            CompanyNo = CompanyTxt.Text != null ? CompanyTxt.Text : "",
                            //Remark = RemarkTxt.Text,
                            ItemRemark = itemRemarkTxt.Text,
                            //Summary = summaryTxt.Text,
                            CreateTime = DateTime.Now,
                            CreatorId = LoginInfo.GetLoginInfo().UserId,
                            CreatorName = LoginInfo.GetLoginInfo().UserName,
                            MakerId = Convert.ToInt32(makerCbx.SelectedValue),
                            MakerName = makerCbx.Text,
                            MakeTime = MakerTime.Value,
                            InstockItemNo = instockNo.Text,
                            Amount = Convert.ToDecimal(costTxt.Text),
                            ColorType = ColorTypeTxt.Text,
                            FinalAmount = Convert.ToDecimal(outmoneyAmountTxt.Text),
                            UnitStr = unitCbb.Text,
                            InstockProductName = productTxt.Text,
                            PayAccountId = outmoneycbb.SelectedValue != null ? (int)outmoneycbb.SelectedValue : 0,
                            //InstockId=Convert.ToInt32(productCbb.SelectedValue),
                            Price = Convert.ToDecimal(priceTxt.Text),
                            Quantity = Convert.ToDecimal(QuanityTxt.Text),
                            IsPaid = isPay == 0 ? false : true,
                            Remark = isPay == 1 ? "手动付款" : "",

                        };
                        dbs.InStockItems.Add(instockItem);
                        result = dbs.SaveChanges();
                    }

                }
                if (result > 0)
                {

                    var saleOrder = db.SaleOrders.Where(o => o.OrderNo == orderNoTxt.Text).FirstOrDefault();
                    var saleOrderItem = db.SaleOrderItems.Where(o => o.Id == _orderItemId).FirstOrDefault();
                    var saleCount = db.SaleOrderItems.Where(o => o.OrderNo == orderNoTxt.Text).Count();
                    var instockItemCount = db.InStockItems.Where(o => o.SaleOrderNo == orderNoTxt.Text).Count();
                    if (saleCount > instockItemCount && saleOrder.Status == (int)Status.Undo)
                    {
                        saleOrder.Status = (int)Status.Doing;
                    }
                    if (saleCount == instockItemCount && saleOrder.Status <= (int)Status.Doing)
                    {
                        saleOrder.Status = (int)Status.Done;
                    }
                    saleOrderItem.OrderItemStatus = (int)ItemStatus.Done;
                    db.SaveChanges();
                    //if (isPay == 1 && isAreadyPay != true)
                    //{
                    //    var selectIndex = outmoneycbb.SelectedIndex;
                    //    if (selectIndex > 0)
                    //    {
                    //        var sel = outmoneycbb.SelectedValue;
                    //        var account = db.CashAccounts.Find((int)sel);
                    //        if (account != null)
                    //        {
                    //            var vari = instockItem.Amount;
                    //            var preAmount = account.Amount;
                    //            account.Amount -= vari;
                    //            account.OriginalAmount = preAmount;
                    //            account.UpdateTime = DateTime.Now;
                    //            var log = new CashAccountLog()
                    //            {
                    //                OriginalAmount = preAmount,
                    //                VariableAmount = -vari,
                    //                MakerId = (int)makerCbx.SelectedValue,
                    //                MakerTime = DateTime.Now,
                    //                CashAccountId = account.Id,
                    //                CurrentAmount = account.Amount,
                    //                CreateTime = DateTime.Now,
                    //                LoginId = LoginInfo.GetLoginInfo().UserId,
                    //                Source = instockItem.InstockItemNo,
                    //                RelatedObject = instockItem.InstockProductName,
                    //                Remark = instockItem.Remark
                    //            };
                    //            db.CashAccountLogs.Add(log);
                    //            db.SaveChanges();
                    //        }
                    //    }
                    //}
                    //else
                    //{

                    //}
                    message = IsNew ? "保存成功！" : "修改成功!";
                    //MessageBox.Show(message);
                }
            }
            catch (Exception error)
            {
                message = "输入有误！";
                MessageBox.Show(message);
            }
            //MessageBox.Show(message + "  将关闭页签！");
            this.DialogResult = DialogResult.OK;
            this.Close();
            //var main = MainFrm.CreateInstrance();
            //var tab = main.Controls.Find("tabControl1", true).FirstOrDefault() as TabControl;
            //var tabControl = tab;
            //if (tab != null)
            //{
            //    tabControl = (TabControl)tab as TabControl;
            //}
            //if (tabControl.SelectedTab.Name != "tabPageMenu")
            //    tabControl.TabPages.Remove(tabControl.SelectedTab);
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void saveBtn_Click(object sender, EventArgs e)
        {
            saveAndPay();
        }
        //改变键盘键enter效果
        #region
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {

            base.ProcessCmdKey(ref msg, keyData);
            switch (keyData)
            {
                case Keys.Enter:
                    SendKeys.Send("{Tab}");
                    break;

                case Keys.F12:
                    if (IsNew || IsPay == false)
                    {
                        saveAndPay(1);
                    };
                    break;
                default:
                    break;
            }
            return false;
        }
        #endregion
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void productCbb_SelectedIndexChanged(object sender, EventArgs e)
        {
            //var selectIndex = productCbb.SelectedIndex;
            //if (selectIndex > 0)
            //{
            //    var sel = productCbb.SelectedValue;
            //    var product = db.InStockProducts.Where(o => o.Id == (int)sel).FirstOrDefault();
            //    if (product != null)
            //    {
            //        priceTxt.Text = product.Price.ToString();
            //    }
            //}
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void QuanityTxt_TextChanged(object sender, EventArgs e)
        {
            //if (IsNew && !string.IsNullOrEmpty(ColorTypeTxt.Text)&& !ColorTypeTxt.Text.Contains("#"))
            //{
            //    string txt = ColorTypeTxt.Text;
            //    ColorTypeTxt.Text = txt + "#";
            //}
            //try
            //{
            //    var q = Convert.ToDecimal(QuanityTxt.Text);
            //    var p = Convert.ToDecimal(priceTxt.Text);
            //    costTxt.Text = (q * p).ToString();
            //    outmoneyAmountTxt.Text = (q * p).ToString();
            //}
            //catch (Exception)
            //{
            //    MessageBox.Show("输入有误！");
            //}

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void paySaveBtn_Click(object sender, EventArgs e)
        {
            var selectIndex = outmoneycbb.SelectedIndex;
            if (selectIndex > 0 && outmoneycbb.SelectedValue != null)
            {
                saveAndPay(1);
            }
            else
            {
                MessageBox.Show("请选择付款方式！");
            }
        }

        private void instockNo_TextChanged(object sender, EventArgs e)
        {

        }

        private void CompanyTxt_TextChanged(object sender, EventArgs e)
        {

        }

        private void CompanyTxt_MouseClick(object sender, MouseEventArgs e)
        {
            var company = new CompanyFrm();
            company.ShowDialog();

            CompanyTxt.Text = !string.IsNullOrEmpty(company.CompanyName) ? company.CompanyName : "";
            companyId.Text = company.CompanyId > 0 ? company.CompanyId.ToString() : "0";
        }

        private void priceTxt_TextChanged(object sender, EventArgs e)
        {
            try
            {
                var q = Convert.ToDecimal(QuanityTxt.Text);
                var p = Convert.ToDecimal(priceTxt.Text);
                costTxt.Text = (q * p).ToString();
                outmoneyAmountTxt.Text = (q * p).ToString();
            }
            catch (Exception)
            {
                MessageBox.Show("输入有误！");
            }

        }

        private void ColorTypeTxt_TextChanged(object sender, EventArgs e)
        {

        }

        private void ColorTypeTxt_TextChanged_1(object sender, EventArgs e)
        {

        }

        private void ColorTypeTxt_Leave(object sender, EventArgs e)
        {
            if (IsNew && !string.IsNullOrEmpty(ColorTypeTxt.Text) && !ColorTypeTxt.Text.EndsWith("#") && ColorTypeTxt.Text.Trim().Length > 0)
            {
                string txt = ColorTypeTxt.Text;
                ColorTypeTxt.Text = txt + "#";
            }
        }

        private void makerCbx_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter || e.KeyChar == (char)Keys.Return)
            {
                e.Handled = true;//屏蔽回车键
            }
        }

        private void makerCbx_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
            {
                e.Handled = true;//屏蔽回车键
            }

        }

        private void makerCbx_Enter(object sender, EventArgs e)
        {


        }
    }
}
